define([
	"UtilDir/util",
	"UtilDir/tool",	
	"UtilDir/combotree",
	"UtilDir/org/selectOrg",
	"UtilDir/dialog",
    "UtilDir/searchBlock",
	"EasyUI","EasyUI-lang"
    ],function(Util,Tool,Combotree,OrgUtil,Dialog,SearchBlock,Theme){

    var sysPath =  getServer() + "/static/app/fwsjcj";

    var groupFormHtml = sysPath + "/siftgroupmanage/views/groupForm.html";
	var getZwController = function(){
		return getServer() + "/platform/org/zws/";
	};
	var getDivisionController = function () {
        return getServer() + "/platform/org/divisions/";
    };
    var docData;
	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		creategpGrid();
        //浏览器窗口大小变化后，表格宽度自适应
        $(window).resize(function(){
            creategpGrid();
        });
        initdivision();
	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            creategpGrid();
        });
        $("#btnReset").click(function () {
            $("#division").val("");
            $("#groupName").val("");
            $("#groupLeaderSearch").val("");
        });
	};
	var creategpGrid = function() {
        $("#gpGrid").datagrid({
            url:getServer() + "/fw/group/page?groupType=1",
			method:"GET",
			fitColumns: true,
			nowrap: false,
//          rownumbers: true,
            columns:[[
				{field:"ck",checkbox:true},
                {field:'groupName',title:'小组名称',width:'24%',align:'center',
                    formatter:function(value,rowData,rowIndex){
                        return '<a href="#" onclick="_editGroup(\'' + rowData.id+ '\');"> '+rowData.groupName+' </a>'
                    }
                },
                {field:'groupLeader',title:'小组组长',width:'25%',align:'center'},
                {field:'groupMember',title:'小组成员',width:'25%',align:'center'},
                {field:'address',title:'小组地区',width:'25%',align:'center'}
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text:"新增分组",
                handler: function(){addGroup()}
            },{
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){deleteGroup()}
            }],
            queryParams:{
//              division: $("#division").val(),
                groupName: $("#groupName").val(),
                groupLeader: $("#groupLeaderSearch").val()
            },
            pagination: true,
            pageSize: 10
        });
    };



	var formValidator = function(){
		$("#groupForm").validate({
			rules : {
				groupName : {
					required :true,
					maxlength:50
				},
				divisionName : {
					required :true,
					maxlength:50
				},
				groupLeader:{
					required :true,
					maxlength:50
				},
                groupMember:{
                	required :true,
					maxlength:500
				}
			},
			messages : {
                groupName : {
					required:"小组名称不允许为空!",
					maxlength:"职务名称长度不可以超过50"
				},
                divisionName : {
                    required:"地区不允许为空!",
                    maxlength:"地区长度不可以超过50"
                },
				groupLeader:{
					required:"组长不允许为空!",
					maxlength:"组长名称长度不可以超过50"
				},
                groupMember:{
					required:"组员不允许为空!",
					maxlength:"组员名称长度不可以超过500"
				}
			}
		});
	};
    var createRelationGrid = function (data) {
        console.log(data)
        $("#deptUserRelationGrid").datagrid({
            data: data,
            columns: [[
                {field: 'userName', title: '组员名称', width: '35%', align: 'left'},
                {field: 'userCode', title: '手机号', width: '35%', align: 'left'},
                {
                    field: "id1",
                    title: '操作',
                    width: '33%',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a onclick="deleteRow(\'' + rowIndex+ '\');">删除</a >';
                    }
                }
            ]],
            pagination: false,
            //pageSize: 10
        });
    };
    window.deleteRow = function (index) {
    	debugger;
        $('#deptUserRelationGrid').datagrid('deleteRow', index);
        var rows=$("#deptUserRelationGrid").datagrid('getRows');
		$("#deptUserRelationGrid").datagrid('loadData',rows);
        
    };

	var getGp = function(id){
		$.ajax({
			url: getServer() + "/fw/group/findById?groupId="+id,
			type: "get",
//			params:{
//				groupId: id
//			},
			success: function (data) {
				debugger;
				console.log(data)
				Tool.deserialize("groupForm", data.fwGroupEntity);
                initDivisionForm();
				createRelationGrid(data.list);
			}
		});
	};

	var addGroup = function () {
		var slidebar = Util.slidebar({
			url: groupFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterOpen: function () {
                createRelationGrid();
            },
			afterLoad: function () {
				initDivisionForm();
				formValidator();
				$("#saveBtn").on("click", function () {
					if($("#groupForm").valid()){
						var data = {};
                        data.fwGroupEntity = Tool.serialize("groupForm");                                              
                        data.list = $("#deptUserRelationGrid").datagrid("getRows");
                        data.fwGroupEntity.groupType = "1";
						debugger;
						if($("#divisionForm").val() == "中华人民共和国"){
						   Util.alert("请选择所属详细地区（除中华人民共和国）");
						    return;
                        }
						if(data.list.length<=0){
						   Util.alert("请将选择小成员添加到列表中");
						    return;
                        }else {
						    $.ajax({
                                url: getServer() + "/fw/group/save/1",
                                contentType:"application/json",
                                data: JSON.stringify(data),
                                type: "post",
                                success: function (data) {
                                    Util.alert(data.message);
                                    slidebar.close();
                                    creategpGrid();
                                }
						    });
					    }
                    }
				});
				$("#addDeptBtn").on("click", function () {                	
                	debugger;
				    var rowsData = $('#deptUserRelationGrid').datagrid('getRows');
				    var arr = [];
				    for (var x = 0 ; x < rowsData.length ; x++) {
				        arr[x] = rowsData[x].userId;
				    }
				    for (var i = 0; i < docData.length; i++) {//循环要添加的数据
				        var flag = false;
				        //当添加的数据之前添加过时，不再添加
				        for (var s in arr) {
				            if (arr[s] == docData[i].userId) {//当数组中有值与要添加的数据相等时flag赋值true
				                flag = true;
				            }
				        }
				        if (flag == false) {  //当数组中无值要与相加的数据相等时进行添加
				            $("#deptUserRelationGrid").datagrid('appendRow', {
		                        userId: docData[i].userId,
		                        userCode: docData[i].mobilePhone,
		                        userName: docData[i].userName,
		                   });		                   
				        }
				       
				    }

                });
			}
		});
	};
	window._editGroup = function(id) {
		var slidebar = Util.slidebar({
			url: groupFormHtml,
			width: "580px",
			cache: false,
			close : true,			
			afterLoad: function () {
                docData="";
				getGp(id);
				
				formValidator();
				
				$("#saveBtn").on("click", function () {
					if($("#groupForm").valid()){						
						var data = {};
                        data.fwGroupEntity = Tool.serialize("groupForm");                                              
                        data.list = $("#deptUserRelationGrid").datagrid("getRows");
                        data.fwGroupEntity.groupType = "1";
						debugger;
						if($("#divisionForm").val() == "中华人民共和国"){
						   Util.alert("请选择所属详细地区（除中华人民共和国）");
						    return;
                        }
                        if(data.list.length<=0){
                            Util.alert("请将选择的小组成员添加到列表中");
                            return;
                        }else {
                            $.ajax({
                                url: getServer() + "/fw/group/updateGroup/1",
                                contentType: "application/json",
                                data: JSON.stringify(data),
                                type: "post",
                                success: function (data) {
                                    Util.alert(data.message);
                                    slidebar.close();
                                    creategpGrid();

                                }
                            });
                        }
					}
				});

				$("#addDeptBtn").on("click", function () {                	
                	debugger;
				    var rowsData = $('#deptUserRelationGrid').datagrid('getRows');
				    var arr = [];
				    for (var x = 0 ; x < rowsData.length ; x++) {
				        arr[x] = rowsData[x].userId;
				    }
				    for (var i = 0; i < docData.length; i++) {//循环要添加的数据
				        var flag = false;
				        //当添加的数据之前添加过时，不再添加
				        for (var s in arr) {
				            if (arr[s] == docData[i].userId) {//当数组中有值与要添加的数据相等时flag赋值true
				                flag = true;
				            }
				        }
				        if (flag == false) {  //当数组中无值要与相加的数据相等时进行添加
				            $("#deptUserRelationGrid").datagrid('appendRow', {
		                        userId: docData[i].userId,
		                        userCode: docData[i].mobilePhone,
		                        userName: docData[i].userName,
		                   });		                   
				        }
				       
				    }

                });
			}
		});
	};
	var deleteGroup = function() {
		var rows = $("#gpGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的小组?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.id + ",";
			});
			ids = ids.substr(0,ids.length - 1);
			debugger;
			$.ajax({
				url: getServer() + "/fw/group/"+ids,
				type: "post",
				success: function (data) {
					Util.alert(data.message);
					creategpGrid();
				}
			});
		}, function() {
			return;
		});

	};
	var initdivision = function () {
		var combotree = Combotree({
            // combo组件相关配置
            combo: {
                //要渲染的input的id
                id: "division",
                //下拉框的类型：单选or多选
                multi: false,
                key: {
                    idKey: "divisionId",
                    textKey: "divisionName"
                },
                //          placeholder: "请选择……",
                event: {
                    onShowPanel: function () {
                        console.log("show");
                    },
                    onHidePanel: function () {
                        console.log("hide");
                    },
                    onChange: function (n, o) {
                    	debugger;
                        $("#divisionId").val(n[0].divisionId);
                        $("#division").val(n[0].divisionName);
                    }
                }
            },
            // ztree组件相关配置
            ztree: {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "divisionId", // 主键属性名
                        pIdKey: "parentId" // 父节点属性名
                    },
                    key: {
                        name: "divisionName" // 显示名称属性名
                    }
                },
                check: {
                    chkboxType: {
                        'Y': '',
                        'N': ''
                    }
                }
            },
            data: {
                url: getDivisionController() + 'initDivisionZtree',
                type: 'GET',
                success: function () {

                }
            },
            formatter: function (node) {
                node.open = false;
            },
            value: $("#divisionId").val(),
            search: {
                enable: true,
                fields: ["divisionName"]
            }
        });
	}
	
	var initDivisionForm = function () {
        //初始化行政岗区划
        var combotree = Combotree({
            // combo组件相关配置
            combo: {
                //要渲染的input的id
                id: "divisionForm",
                //下拉框的类型：单选or多选
                multi: false,
                key: {
                    idKey: "divisionId",
                    textKey: "divisionName"
                },
                //          placeholder: "请选择……",
                event: {
                    onShowPanel: function () {
                        console.log("show");
                    },
                    onHidePanel: function () {
                        console.log("hide");
                    },
                    onChange: function (n, o) {
                        $("#divisionId").val(n[0].divisionId);
                        $("#divisionForm").val(n[0].divisionName);
                    }
                }
            },
            // ztree组件相关配置
            ztree: {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "divisionId", // 主键属性名
                        pIdKey: "parentId" // 父节点属性名
                    },
                    key: {
                        name: "divisionName" // 显示名称属性名
                    }
                },
                check: {
                    chkboxType: {
                        'Y': '',
                        'N': ''
                    }
                }
            },
            data:{
                url: getDivisionController() + 'initDivisionZtree',
                type: 'GET',
                success: function (res) {
					
                }
			},

            formatter: function (node) {
                node.open = false;
            },
            value: $("#divisionId").val(),
            search: {
                enable: true,
                fields: ["divisionName"]
            }
        });
        var userId = $("#groupLeaderId").val();
        debugger;
        OrgUtil.init({
            id: "groupLeaderName",
            multi: false,
            title: "请选择人员",
            hideTag: true,
            tagType: ["user"],
            data:{
            	"user":[{userId:userId}]
            },
            callback: function (data) {
                $("#groupLeaderId").val(data.user[0].userId);
                $("#groupLeaderName").val(data.user[0].userName);
            }
        });
        
        OrgUtil.init({
            id: "groupMember",
            multi: true,
            title: "请选择人员",
            hideTag: true,
            tagType: ["user"],
            callback: function (data) {
            	debugger;
//          	$("#groupUserId").val(data.user[0].userId);
//              $("#groupMember").val(data.user[0].userName);
//              $("#groupMobilePhone").val(data.user[0].mobilePhone);
                docData = data.user;
            	var rows = data.user;
                var members = "";
                var membersIds = "";
				$.each(rows, function(i, row){
					members += row.userName + ",";
					membersIds += row.userId + ",";
				});
				members = members.substr(0,members.length - 1);
                $("#groupMember").val(members); 
                
//				membersIds = membersIds.substr(0,membersIds.length - 1);
//              $("#groupUserId").val(membersIds);
            }
        });
   	};
	return {
		init:init
	};
});
